<?php
$p = 'topics';
$options = array ();
CHtml::resolveNameID($model, $p, $options);

$cs = Yii::app()->clientScript;

$script =<<<EOL
function after_reload()
{
  jQuery.tree.plugins.checkbox.get_checked().each(function(){
		if(jQuery(this).show_comment != undefined && jQuery(this).show_comment != null)
			jQuery(this).show_comment();
  });
}
EOL;

foreach ($model->topics as $topic => $weeks) {
	$script .= '  jQuery.tree.plugins.checkbox.check($("#node_' . $topic . '")[0]);' . "\n";
}

$script .= "after_reload()";
?>
<div class="yiiForm">

<?php $this->widget('application.components.RequiredMessage'); ?>


<?php


echo CHtml::beginForm('', 'post', array (
	'id' => "topics_selection"
));

echo Yii::t('views', 'Topics available');

$this->printHiddenField($model);

echo CHtml::activeHiddenField($model, 'form_type');
echo CHtml::errorSummary($model);

$this->Widget('application.extensions.jsTree.CjsTree', array (
	'htmlOptions' => array (
		'id' => 'topics_tree'
	),
	'ui' => array (
		'theme_name' => 'checkbox'
	),
	'options' => array (
		'plugins' => array (
			'checkbox' => array (
				'three_state' => 'true'
			)
		)
	),
	'genDiv' => false,
	'callback' => array (
		'onload' => "js:function() { \n" .
		"$script" .
		"}",
		'oncheck' => "js:function(NODE) { \n" .
		"  if (NODE.children('img').length > 0)\n" .
		"  {\n" .
		"    NODE.trigger('show_image'); \n" .
		"    NODE.trigger('show_comment'); \n" .
		"  }else{\n" .
		"    NODE.children('ul').children('li.node').trigger('show_image').trigger('show_comment'); \n" .
		"  }\n" .
		"  NODE.find('div[id^=weeks_layer]').show().attr('style', 'display:inline;');\n" .
		"}\n",
		'onuncheck' => "js:function(NODE) { \n" .
		"  if (NODE.children('img').length > 0)\n" .
		"  {\n" .
		"    NODE.trigger('hide_image'); \n" .
		"  }else{\n" .
		"    NODE.children('ul').children('li.node').trigger('hide_image'); \n" .
		"  }\n" .
		"  NODE.find('div[id^=weeks_layer]').hide();\n" .
		"}\n"
	)
));
?>

<div id="topics_tree">
<?php


displaySteps($this, $model, $route->steps);
?>
</div>

<div class="action">
<?php echo CHtml::submitButton(Yii::t('views', 'Create')); ?>
</div>

<?php echo CHtml::endForm(); ?>

</div><!-- yiiForm -->
<?php


function displaySteps($p, $model, $steps) {
	if (is_array($steps) && count($steps) > 0) {
		echo "<ul style='width:100%;'>";
		foreach ($steps as $step) {
			echo "<li id='node_" . $step->id . "' class='open node' style='width:100%;'>\n";
			echo "\t<a href='#'><ins>&nbsp;</ins>" . $step->label . "</a>";
			displayTopics($p, $model, $step->topics);
			echo CHtml::hiddenField("step_weeks[" . $step->id . "]", "8", array (
				'id' => 'step_weeks_' . $step->id,
				'size' => '3',
				'maxlength' => '3'
			));
			echo "</li>";
		}
		echo "</ul>";
	}
}

function displayTopics($p, $model, $topics) {
	if (is_array($topics) && count($topics) > 0) {
		echo "<ul style='width:100%;'>";
		foreach ($topics as $topic) {
			echo "<li id='node_" . $topic->id . "' class='node'>\n" .
			"\t<a href='#'><ins>&nbsp;</ins></a>\n\t" .
			CHtml::image('images/arrow_down_blue.png', 'Show/Hide validation comments', array (
				'onclick' => 'javascript:$("#' . $topic->id . '").trigger("toggle_comment")',
				'id' => 'img_comment_' . $topic->id
			)) . "\n\t" .
			"\n\t<a href='#'>" . $topic->label . "  " . $topic->id . "</a>" .
			"<div id=\"weeks_layer_" . $topic->id . "\" class=\"weeks_layer\">:&nbsp;<input type=\"text\" value=\"" . $topic->weeks_number . "\" id=\"weeks_" . $topic->id . "\" name=\"weeks[" . $topic->id . "]\" size=\"3\"/>".
			Yii::t('project', 'weeks to end')."</div>\n\t";
			$p->widget('adviser.widgets.CommentLayer', array (
				'topic_id' => $topic->id,
				'columns' => 60,
				'rows' => 5,
				'prefix' => '',
				'adviser_validation' => isset ($model->adviser[$topic->id]),
				'adviser_topic_validation' => isset ($model->adviser_validation[$topic->id]) ? $model->adviser_validation[$topic->id] : "",
				'owner_validation' => isset ($model->owner[$topic->id]),
				'owner_topic_validation' => isset ($model->owner_validation[$topic->id]) ? $model->owner_validation[$topic->id] : "",
				'comment' => isset ($model->comment[$topic->id]) ? $model->comment[$topic->id] : "",
				'form_name' => "topics"
			));
			displayTopics($p, $model, $topic->topics);
			echo "<input type=\"hidden\" value=\"" . $topic->id . "\" id=\"topics_" . $topic->id . "\" name=\"topics[" . $topic->id . "]\" size=\"3\"/></li>";
		}
		echo "</ul>";
	}
}

$cs->registerScriptFile(Yii::app()->baseUrl . '/js/masks.js', CClientScript::POS_HEAD);
$cs->registerScriptFile(Yii::app()->baseUrl . '/js/topic_validation.js', CClientScript::POS_HEAD);

$name = $options['name'];
$script =<<<EOL

function renameInputs(id)
{
	$('#topics_'+id).attr('name', 'NewProjectForm[topics]['+id+']');
	$('#adviser_'+id).attr('name', 'NewProjectForm[adviser]['+id+']');
	$('#owner_'+id).attr('name', 'NewProjectForm[owner]['+id+']');
	$('#adviser_validation_'+id).attr('name', 'NewProjectForm[adviser_validation]['+id+']');
	$('#owner_validation_'+id).attr('name', 'NewProjectForm[owner_validation]['+id+']');
	$('#comment_'+id).attr('name', 'NewProjectForm[comment]['+id+']');
	$('#weeks_'+id).attr('name', 'NewProjectForm[weeks]['+id+']');
}
function submit_form(object_name)
{
  $("input[id^='adviser_']").attr("disabled", false);
  $("input[id^='owner_']").attr("disabled", false);

  var topics = new Array();
  jQuery.tree.plugins.checkbox.get_checked().each(function(){
  		var id = this.id.replace ('node_', '');
  		renameInputs(id);
  });

  jQuery.tree.plugins.checkbox.get_undeterminded().each(function(){
  		var id = this.id.replace ('node_', '');
  		renameInputs(id);
  });

}


$("#topics_selection").bind("submit", function(){
  submit_form("$name");
});/*
$("input[id^='adviser_']").live("click", function(){
	var id = 'node_'+jQuery(this).attr('id').replace(/adviser_/, '');
	var v = jQuery.find_topic(id);
	if (v){
		v.adviser_validate(jQuery(this).is(":checked"));
		v.adviser_checkbox().attr("disabled", false);
		v.comment_area().attr("readonly", false);
	}
});
$("input[id^='owner_']").live("click", function(){
	var id = 'node_'+jQuery(this).attr('id').replace(/owner_/, '');
	var v = jQuery.find_topic(id);
	if (v){
		v.owner_validate(jQuery(this).is(":checked"));
		v.owner_checkbox().attr("disabled", false);
		v.comment_area().attr("readonly", false);
	}
});
$("input[id^=w_]").live('focusout', function(){
	var id = 'node_'+jQuery(this).attr('id').replace(/w_/, '');
	var v = jQuery.find_topic(id);
	if (v){
		v.weeks_changed(jQuery(this).val());
	}
})*/

function getMaxWeeks(input)
{
  max = 0;
  // move to <div id="weeks_layer_??" ...>
  $(input).parent()
    // move to <li>
    .parent()
    // find children
    .children('ul')
    // move to <input id='weeks_'>
    .find("input[id^='weeks_']")
    .each(function()
    {
      value = parseInt(this.value,10);
      if (value > max)
        max = value;
    });

    return max;
}

function updateMaxWeeks(weeks, oldValue)
  {
    var value=parseInt(weeks.value,10);
    weeks.oldValue=oldValue;

    if (value != oldValue)
    {
      // move to <div id="weeks_layer_??" ...>
      $(weeks).parent()
        // move to <li>
        .parent()
        // find children
        .children('ul')
        // move to <input id='weeks_'>
        .children("li").children("div").children("input[id^='weeks_']")
        // For each textfield
        .each(function()
        {
          if (parseInt(this.value,10) > value)
          {
            this.value = value;
            $(this).trigger('change');
          }
		  else if (parseInt(this.value,10) == oldValue)
          {
   		    this.value = value;
            $(this).trigger('change');
          }
          this.oldValue = value;
        });

      // update all parents
      // move to <div id="weeks_layer_??" ...>
      var p = $(weeks).parent()
        // move to <li>
        .parent()
        // move to parent li
        .parent().parent()
        // get <input id='weeks_'> for the parent
        .children("div").children("input[id^='weeks_']")
      var upd = p.length > 0;

      while (upd)
      {
        p.each(function()
        {
          max = getMaxWeeks(weeks);
          if (parseInt(weeks.value,10) != max)
          {
            this.value = max;
            this.oldValue = max;
            $(this).trigger('change');
            upd = true;
          }else{
            upd = false;
          }
        });

        // move to <div id="weeks_layer_??" ...>
        p = p.parent()
          // move to <li>
          .parent()
          // move to parent li
          .parent().parent()
          // get <input id='weeks_'> for the parent
          .children("div").children("input[id^='weeks_']")

        upd = upd && p.length > 0;
      }

      $(weeks).parent()
        // move to <li>
        .parent()
        // move to parent li
        .parent().parent()
        // get <input id='weeks_'> for the parent
        .children("div").children("input[id^='weeks_']")
        .each(function()
        {
          max = getMaxWeeks(this);
          if (parseInt(this.value,10) != max)
          {
            this.value = max;
            this.oldValue = max;
            $(this).trigger('change');
          }
        });
      }
  }

$("input[id^='weeks_']")
  .each(function(){ this.oldValue = parseInt(this.value,10); })
  .live("change", function (event) {
  updateMaxWeeks(this, this.oldValue);
  });


$("div[id^='weeks_layer_']").hide();
$("div[id^='comment_layer_']").hide();
$("img[id^='img_comment_']").hide();

$("input[id^='weeks_']")
	.each(function() {
      // move to <div id="weeks_layer_??" ...>
	  weeks = $(this).parent()
        // move to <li>
        .parent()
        // find children
        .children('ul');
      
      if (weeks.length == 0) {
        updateMaxWeeks(this, 0);
      }
	});
init_topics($("#topics_tree"),"");


EOL;

$cs->registerScript('topics_form_save', $script);
?>




<?php

/*

displaySteps2($route->steps);


function displaySteps2($steps) {
	if (is_array($steps) && count($steps) > 0) {
		echo "<ul style='width:100%;'>";
		foreach ($steps as $step) {
			echo "<li>\n" . $step->label;
			displayTopics2( $step->topics);
			echo "</li>";
		}
		echo "</ul>";
	}
}

function displayTopics2($topics) {
	if (is_array($topics) && count($topics) > 0) {
		echo "<ul style='width:100%;'>";
		foreach ($topics as $topic) {
			echo "<li>" . $topic->label;
			displayTopics2($topic->topics);
			echo "</li>";
		}
		echo "</ul>";
	}
}

   $(this).parent().parent().parent().parent().children("div").children("input[id^='weeks_']")


*/


/*

   .parent().children('ul').children("li").children("div").children("input[id^='weeks_']")

   this.weeks_field().live("change", function(){
   var v = jQuery.find_topic('node_'+jQuery(this).attr('id').replace (/w_/, ""));
   if (v)
   v.week_changed(jQuery(this).val())
   });


   this.week_changed=function(val,rChild,rParent){
		// if value > parent value, we update it
		val = parseInt (val,10);
		if (val != this.weeks_number){
			if (rParent !== false){
				if (this.parent_topic()){
					if (this.parent_topic().weeks_number <= val){
						this.parent_topic().week_changed(val,false, true);
					}
				}
			}

			if (rChild !== false){
				// we update all children that have the same weeks number
				var c = this.children_topics();
				for (var i=0 ; i < c.length ; i++){
					if (c[i].weeks_number >= this.weeks_number){
						c[i].week_changed(val, true, false);
					}
				}
			}
		}

		this.weeks_number = val;
		this.weeks_field().val(this.weeks_number);
	}


*/
?>
